/*
 * win32.cpp
 *
 *  Created on: 2012-8-30
 *      Author: yangentao@gmail.com
 */

#include "win32.h"
#include <ole2.h>

#include "DataObjectImpl.h"

bool isKeyDown(int key) {
	return (::GetKeyState(key) & 0x80000000) != 0;
}

long getTimeTick(){
	return ::GetTickCount();
}

//IsClipboardFormatAvailable/OpenClipboard/GetClipboardData
String getClipboardText() {
	String s;
	IDataObject* data = 0;
	if (::OleGetClipboard(&data) != S_OK ) {
		return s;
	}
	FORMATETC formatEtc = { 0 };
	formatEtc.cfFormat = CF_TEXT; //TODO CF_UNICODETEXT
	formatEtc.ptd = 0;
	formatEtc.dwAspect = DVASPECT_CONTENT;
	formatEtc.lindex = -1;
	formatEtc.tymed = TYMED_HGLOBAL;

	STGMEDIUM store;
	if (data->GetData(&formatEtc, &store) == S_OK ) {
		char* buf = (char*) GlobalLock(store.hGlobal);
		s.copyStr(buf, strlen(buf));
		GlobalUnlock(store.hGlobal);
		ReleaseStgMedium(&store);
	} else {
		//TODO Unicode
	}

	data->Release();

	return s;
}

bool setClipboardText(String s, bool unicode) {
	//TODO unicode
	IDataObject* pDataObject = CreateDataObject(s.getBufferRead(), s.length());
	if (pDataObject) {
		OleSetClipboard(pDataObject);
		OleFlushClipboard();
		pDataObject->Release();
		return true;
	}
	return false;
}

HGLOBAL DupMem(HGLOBAL hMem) {
	void* pMem = GlobalLock(hMem);
	int size = GlobalSize(hMem);
	HGLOBAL h = GlobalAlloc(GMEM_FIXED, size);
	if (h) {
		void* p = GlobalLock(h);
		memmove(p, pMem, size);
		GlobalUnlock(h);
	}
	GlobalUnlock(hMem);
	return h;
}
